// pages/xuecar/appointment.js
const app = getApp();
var isclick = 1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    listInfo: [],
    bannerList: [],
    activeBannerIndex: 1,
    submitname:'确定预约',
    showModalStatus: false,
    animationData: '',
    isLoginAuth: false,
    isshow:false,
    today:'',
    tomorrow: '',
    tomorrow1: '',
    tomorrow2: '',
    week1: '',
    week2: '',
    week3: '',
    week4: '',
    teacher:'',
    teacher_id: 0,
    addr: '',
    school: '',
    theaderImg: '',
    planernum:0,
    sheaderImgs: [
        { url: "../../images/my.png"},
        { url: "../../images/my.png" },
        { url: "../../images/my.png" },
        { url: "../../images/my.png" },
    ],
    orderid:0,
    vindex: 1,
    iindex:0,
    seldateArr:[],
    seldatainfo:'',
    ampmArr: ['08:00-12:00', '13:00-18:00'],
    selampminfo: '',
    plantime:[],
    isplan:1, //是否可以预约，满4人后不能预约
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      if (!app.globalData.isLoginAuth) {
        this.showModal();
      }
      this.setData({
        isLoginAuth: app.globalData.isLoginAuth,
        isshow: !app.globalData.isLoginAuth
      })
      this.getDatelist();
      this.setData({
        selampminfo: this.data.ampmArr[this.data.vindex-1],
        seldatainfo: this.data.seldateArr[this.data.iindex+1]
      })
      
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this;
    if (app.globalData.isLoginAuth){
      var uid = wx.getStorageSync('userId');
      wx.request({
        url: app.globalData.hostUrl + 'member/getfansinfo',
        data: {
          id: uid
        },
        success: function (res) {
          var name = res.data.result.realname;
          var mobile = res.data.result.phone;
          if (name == '' || mobile == '') {
            wx.showModal({
              content: '对不起，请先填写【个人资料】中的真实姓名和手机号码！',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../myself/info',
                  })
                }
              }
            });
          }
          else{
            that.checkOrder();
          }
        }
      })
    }
    
    this.setData({
      listInfo: app.globalData.listInfo
    })
      //检查已经预约的信息
    this.initBanner();
  },
    //广告图片初始化
    initBanner: function () {
        var that = this;
        var requrl = app.globalData.hostUrl + 'common/banner';
        var imgbanner = wx.getStorageSync('ycBanner');
        //console.log(imgbanner.length);
        if (!app.expiratTime('ycBanner') || imgbanner.length == 0) {
            wx.request({
                url: requrl,
                data: { 'location': '303' },
                header: {
                    'grant-appid': app.globalData.appid
                },
                success: function (res) {
                    if (res.statusCode === 200) {
                        wx.setStorageSync('ycBanner', res.data.result);
                        that.setData({
                            bannerList: res.data.result
                        })
                    }
                }
            })
        }
        else {
            that.setData({
                bannerList: imgbanner
            })
        }
    },
  selv:function(e){
      var index = e.currentTarget.dataset.vid;
      this.setData({
        vindex: index,
        seldatainfo: this.data.seldateArr[index]
      })
      this.checkTeacherisfull();
  },
  selitem: function (e) {
        var index = e.currentTarget.dataset.iid;
        this.setData({
          iindex: index,
          selampminfo: this.data.ampmArr[index]
        })
        this.checkTeacherisfull();
  },
  getDatelist:function(){
      var dateArr = [];
      var plandate=[];
      for(var i=0;i<4;i++){  
          var date = new Date();
          date.setTime(date.getTime() + i * 24 * 60 * 60 * 1000);

          var year = date.getFullYear()
          var month = date.getMonth() + 1
          var day = date.getDate()

          if (month < 10)
              month = '0' + month;
          if (day < 10)
              day = '0' + day;
 
          var datename = month + "-" + day;
          var tomorrow_full = year + "-" + datename;
          plandate.push(tomorrow_full);
          var week = new Date(tomorrow_full).getDay();
          if(i==0){
              var week1= this.changeWeek(week);
              this.setData({
                  today: datename,
                  week1: week1
              })
              dateArr[i] = datename + ' 星期' + week1;
          }
          else if(i==1){
              var week2 = this.changeWeek(week);
              this.setData({
                  tomorrow: datename,
                  week2: week2
              })
            dateArr[i] = datename + ' 星期' + week2;
          }
          else if (i == 2) {
              var week3=this.changeWeek(week);
              this.setData({
                  tomorrow1: datename,
                  week3: week3
              })
            dateArr[i] = datename + ' 星期' + week3;
          }
          else if (i == 3) {
              var week4 = this.changeWeek(week);
              this.setData({
                  tomorrow2: datename,
                  week4: week4
              })
            dateArr[i] = datename + ' 星期' + week4;
          }
      }
      this.setData({
        seldateArr: dateArr,
        plantime: plandate
      })
  },
  changeWeek:function(week){
     var weekname=''; 
     switch(week){
         case 0:
            weekname='日';
         break;
         case 1:
             weekname = '一';
             break;
         case 2:
             weekname = '二';
             break;
         case 3:
             weekname = '三';
             break;
         case 4:
             weekname = '四';
             break;
         case 5:
             weekname = '五';
             break;
         case 6:
             weekname = '六';
             break;
     }
     return weekname;
  },
  //查看教练是否已经被预约满员
  checkTeacherisfull:function(){
    var that = this;
    var requrl = app.globalData.hostUrl + 'handler/checkTeacherisfull';
    var getdata={
      'userid': wx.getStorageSync('userId'),
      'tid': this.data.teacher_id,
      'plantime': this.data.plantime[this.data.vindex],
      'ampm': this.data.ampmArr[this.data.iindex]
    }
    //console.log(getdata);
    wx.request({
      url: requrl,
      data: getdata,
      header: {
        'grant-appid': app.globalData.appid
      },
      success: function (res) {
        var studenter=res.data.result;
        if (studenter.length>4){
            that.setData({
              isplan:0
            })
        }
        var imgArr = [
          { url: "../../images/my.png" },
          { url: "../../images/my.png" },
          { url: "../../images/my.png" },
          { url: "../../images/my.png" }
        ];
        for (var i = 0; i < studenter.length;i++){
          imgArr[i].url = studenter[i].headimgurl;
        }
        that.setData({
          sheaderImgs: imgArr,
          planernum: studenter.length
        })
      }
    })
  },
  //检查用户是否已经提交过报名订单
  checkOrder:function(){
      var that=this;
      var requrl = app.globalData.hostUrl + 'handler/checkOrder';
      wx.request({
          url: requrl,
          data: { 'userid': wx.getStorageSync('userId')},
          success: function (res) {
//            console.log(res);
              var showmodel=0;
              var tip='';
              var cfText='';
              var gotourl='';
              if (res.data.code == -1) {
                  showmodel = 1;
                  tip = '目前您还没有报名学车订单！';
                  cfText = '去报名';
                  gotourl ='/pages/xuecar/signup?tid=0'
              }
              else if(res.data.code == -2) {
                  showmodel = 1;
                  tip = '订单还未支付！';
                  cfText = '去支付';
                  gotourl = '/pages/xuecar/orderdetail?oid='+res.data.result.id
              }
              else if (res.data.code == -3) {
                  showmodel = 1;
                  tip = '学车报名订单还未完成！';
                  cfText = '查看订单';
                  gotourl = '/pages/xuecar/orderdetail?oid=' + res.data.result.id
              }
              else if (res.data.code == -4) {
                  showmodel = 1;
                  tip = '您的报名订单客服正在确认中，请等待！';
                  cfText = '查看订单';
                  gotourl = '/pages/xuecar/orderdetail?oid=' + res.data.result.id
              }
              else if (res.data.code == -5) {
                showmodel = 1;
                tip = '您的报名订单教练正在接单中，请等待！';
                cfText = '查看订单';
                gotourl = '/pages/xuecar/orderdetail?oid=' + res.data.result.id
              }
              else if (res.data.code == 200){
                  that.setData({
                    orderid: res.data.result.id,
                    teacher: res.data.result.realname,
                    teacher_id: res.data.result.tid,
                    addr: res.data.result.areaname,
                    school: res.data.result.sname,
                    theaderImg: res.data.result.headimgurl,
                  })
                  that.checkTeacherisfull();
              }
              if(showmodel==1){
                wx.showModal({
                    title: '提示',
                    content: tip,
                    showCancel: true,
                    cancelText: '关闭',
                    confirmText: cfText,
                    success(res) {
                        if (res.confirm) {
                            wx.navigateTo({
                              url: gotourl,
                            })
                        } else if (res.cancel) {
                            wx.navigateTo({
                                url: '/pages/xuecar/learncar',
                            })
                        }
                    }
                })
                that.setData({
                    isshow: true
                })
              }

          }
      })
  },
  formSubmit: function (e) {
    var requrl = app.globalData.hostUrl + 'handler/planxc';
    var postdata={
      'oid':this.data.orderid,
      'openid': wx.getStorageSync('openId'),
      'userid': wx.getStorageSync('userId'),
      'tid': this.data.teacher_id,
      'planinfo': this.data.seldatainfo + ' ' + this.data.selampminfo,
      'plantime': this.data.plantime[this.data.vindex],
      'ampm': this.data.ampmArr[this.data.iindex],
      'formid' : e.detail.formId
    }
    //console.log(postdata);
    if (this.data.isplan==0){
      wx.showToast({
        title: '预约已满员',
        icon: 'error',
        duration: 2000
      })
      return false;
    }

    if(isclick==1){
        isclick=0;
        wx.request({
          url: requrl,
          data: postdata,
          header: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'grant-appid': app.globalData.appid
          },
          method: 'POST',
          success: function (res) {
            //console.log(res);
            if (res.data.code == 200) {
              wx.showModal({
                title: '提示',
                content: '预约成功',
                success(res) {
                  wx.navigateTo({
                    url: '/pages/xuecar/index',
                  })
                }
              })
            }
            else if (res.data.code == 201){
              wx.showToast({
                title: '预约失败',
                icon: 'error',
                duration: 2000
              })
              isclick = 1;
            }
            else if (res.data.code == 202) {
              wx.showToast({
                title: '预约已存在',
                icon: 'success',
                duration: 2000
              })
              isclick = 1;
            }
            else if (res.data.code == 203) {
              wx.showToast({
                title: '无效订单',
                icon: 'error',
                duration: 2000
              })
              isclick = 1;
            }
            else if (res.data.code == 203) {
              wx.showModal({
                title: '提示',
                content: '获取用户信息失败',
                success(res) {
                  wx.redirectTo({
                    url: '/pages/wxauth/wxauth',
                  })
                }
              })
            }
            isclick = 1;
          }
        })
    }
  },
  calling: function (e) {
    var mobile = '15916351997';
    wx.makePhoneCall({
      phoneNumber: mobile,
      success: function () {
        //console.log("拨打电话成功！")
      },
      fail: function () {
        // console.log("拨打电话失败！")
      }
    })
  },
  gohome: function () {
    wx.redirectTo({
      url: '../index/index',
    })
  },
  yuy: function () {
    if (1 == wx.getStorageSync('roleidentity')) {
      wx.redirectTo({
        url: '../myself/thappointment',
      })
    }
    else {
      wx.redirectTo({
        url: '../myself/myappointment',
      })
    }
  },
  orders: function () {
    if (1 == wx.getStorageSync('roleidentity')) {
      wx.redirectTo({
        url: '../myself/trorder',
      })
    }
    else {
      wx.redirectTo({
        url: '../myself/myorder',
      })
    }
  },
  mys: function () {
    wx.redirectTo({
      url: '../myself/myself',
    })
  },
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease-in-out",
      delay: 0
    })
    this.animation = animation
    animation.translateY(500).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    this.setData({
      showModalStatus: false,
    })
  },
  bindGetUserInfo: function (e) {
    console.log(e);
    if (e.detail.errMsg == 'getUserInfo:ok') {
      app.globalData.userInfo = e.detail.userInfo;
      app.getfansinfo();
    }
    else if (e.detail.errMsg == "getUserInfo:fail auth deny") {

    }
    else {
      wx.redirectTo({
        url: '../xuecar/index',
      })
    }
  }
})